package com.vigor.bear.web.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vigor.bear.web.bean.JsonModel;
import com.vigor.bear.web.bean.SessionModel;
import com.vigor.bear.web.constants.Constants;
import com.vigor.bear.web.utils.DatatableUtils;

@Controller
@RequiresPermissions("session:*")
@RequestMapping("/session")
public class SessionController {

	@Autowired
	private SessionDAO sessionDao;

	@RequestMapping(method = RequestMethod.GET)
	public String view() {
		return "system/session/list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> list(@RequestBody String aoData) {
		// 获取当前活动的session列表
		Collection<Session> sessions = sessionDao.getActiveSessions();

		// 获取Datatable中的sEcho参数
		JSONArray jsonarray = JSONArray.parseArray(aoData);
		String sEcho = null;
		for (int i = 0; i < jsonarray.size(); i++) {
			JSONObject obj = (JSONObject) jsonarray.get(i);
			if (obj.get("name").equals("sEcho"))
				sEcho = obj.get("value").toString();
		}

		return DatatableUtils
				.getQueryResult(sEcho, buildSessionModel(sessions));
	}

	@RequestMapping("/{sessionId}/forceLogout")
	@ResponseBody
	public JsonModel forceLogout(@PathVariable("sessionId") String sessionId,
			JsonModel json) {
		try {
			Session session = sessionDao.readSession(sessionId);
			if (session != null) {
				session.setAttribute(Constants.SESSION_FORCE_LOGOUT_KEY,
						Boolean.TRUE);
			}
		} catch (Exception e) {/* ignore */
		}
		json.setSuccess(true);
		json.setMessage("强制退出成功");
		return json;
	}

	@RequestMapping("/forceLogoutSelect")
	@ResponseBody
	public JsonModel forceLogoutSelect(@RequestParam("ids") String ids,
			JsonModel json) {
		try {
			for (String sessionId : ids.split(",")) {
				Session session = sessionDao.readSession(sessionId);
				if (session != null) {
					session.setAttribute(Constants.SESSION_FORCE_LOGOUT_KEY,
							Boolean.TRUE);
				}
			}
		} catch (Exception e) {/* ignore */
		}
		json.setSuccess(true);
		json.setMessage("强制退出成功");
		return json;
	}

	private List<SessionModel> buildSessionModel(Collection<Session> sessions) {
		List<SessionModel> list = new ArrayList<SessionModel>();
		int index = 0;
		for (Session session : sessions) {
			PrincipalCollection principalCollection = (PrincipalCollection) session
					.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (principalCollection == null)
				continue;

			SessionModel sessionModel = new SessionModel();
			sessionModel.setUser((String) principalCollection
					.getPrimaryPrincipal());
			sessionModel.setRecid(++index);
			sessionModel.setId(session.getId().toString());
			sessionModel.setHost(session.getHost());
			sessionModel.setLast(session.getLastAccessTime());
			sessionModel.setForce(session
					.getAttribute(Constants.SESSION_FORCE_LOGOUT_KEY) != null);

			list.add(sessionModel);
		}
		return list;
	}

}
